package com.aviation.sell_ticket.tool;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.stereotype.Component;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
public class SocketIOHandler {

    private static Map<String, SocketIOClient> concurrentHashMap = new ConcurrentHashMap<>();

    @OnConnect
    public void onConnect(SocketIOClient client){
        String userId = client.getHandshakeData().getSingleUrlParam("token");
        if(userId!=null){
            concurrentHashMap.put(userId,client);
        }
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client){
        String userId = client.getHandshakeData().getSingleUrlParam("token");
        concurrentHashMap.remove(userId);
    }

    @OnEvent("chatevent")
    public void chatEvent(SocketIOClient client, AckRequest ackRequest, String message){
        System.out.println(message);
        client.sendEvent("talk","要你管？");
    }

    public void forcedReturn(String sessionId){
        SocketIOClient ioClient = concurrentHashMap.get(sessionId);
        if(null!=ioClient){
            ioClient.sendEvent("forcedReturn",ResultUtil.success(ResultEnum.FORCED_RETURN,null));
            concurrentHashMap.remove(sessionId);
        }
    }
}
